using UnityEngine;
using System.Collections;

[RequireComponent(typeof(AudioSource))]

public class FlightParticleController : MonoBehaviour
{
	public float litAmount = 0.0f;

	public IEnumerator Start()
	{
		ThirdPersonController playerController = this.GetComponent<ThirdPersonController>();
		
		//Ensure an AudioSource is always attached
		
		audio.loop = false;
		audio.Stop();
		
		//Initialize the particles to not emit and switch off spotlights
		Component[] particles = GetComponentsInChildren<ParticleEmitter>();
		Light childLight =GetComponentInChildren<Light>();
		
		foreach(ParticleEmitter p in particles)
		{
			p.emit = false;
		}
		
		childLight.enabled = false;
		
		//Once every frame update particle emission and lights
		
		while(true)
		{
			//Cache value of IsJumping() in isFlying
			bool isFlying = playerController.IsJumping();
			
			if(isFlying)
			{
				if(!audio.isPlaying)
				{
					audio.Play();
				}
			}
			else
			{
				audio.Stop();
			}
			
			foreach(ParticleEmitter p in particles)
			{
				p.emit = isFlying;
			}
			
			if(isFlying)
			{
				litAmount = Mathf.Clamp01(litAmount - Time.deltaTime * 2);
			}	
			else
			{
				litAmount = Mathf.Clamp01(litAmount - Time.deltaTime *2);
			}
				childLight.enabled = isFlying;
				childLight.intensity = litAmount;
			
			yield return null;
			
		}
	}
}